<?php

namespace App\Admin\Forms;

use App\Models\Order\GoodsOrder;
use App\Service\OrderService;
use Dcat\Admin\Admin;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use EasyWeChat\Pay\Application;
use Illuminate\Support\Facades\Log;

class GoodsOrderRefunds extends Form implements LazyRenderable
{
    use LazyWidget;

    public function handle(array $input)
    {
        $id = $this->payload['id'] ?? null;
        $orderService = new OrderService();
        $error = $orderService->refund($id, Admin::user()->id, $input['refund_reason']);
        if ($error) {
            return $this->response()->error(trans('errmsg.api.'.$error.'.1'));
        }
        return $this
            ->response()
            ->success('退款成功')
            ->refresh();
//        $goodsOrder = GoodsOrder::find($id);
//        $orderSamples = $goodsOrder->samples;
//        foreach ($orderSamples as &$orderSample) {
//            if ($orderSample->status != 1) {
//                return $this->response()->error('存在已预约的样本，无法退款');
//            }
//        }
//        $config = config('wechatpay');
//        $app = new Application($config);
//        $response = $app->getClient()->postJson("v3/refund/domestic/refunds", [
////            "transaction_id" => $goodsOrder->order_no,
//            "out_trade_no" => $goodsOrder->order_no,
//            "out_refund_no" => $goodsOrder->order_no,
//            "reason" => $input['refund_reason'],
//            "notify_url" => url('api/v1/mini/payment_notify'),
//            "funds_account" => "AVAILABLE",
//            "amount" => [
//                "refund" => intval($goodsOrder->final_price * 100),
////                "from" => [
////                    "account" => "AVAILABLE",
////                    "amount" => 1
////                ],
//                "total" => intval($goodsOrder->final_price * 100),
//                "currency" => "CNY"
//            ],
//        ]);
//        $refundResp = $response->toArray(false);
//        if (!@$refundResp['refund_id']) {
//            Log::debug('退款失败', $refundResp);
//            return $this->response()->error('退款失败');
//        }
//        $goodsOrder->refund_id = $refundResp['refund_id'];
//        $goodsOrder->refund_reason = $input['refund_reason'];
//        $goodsOrder->refund_operator_id = Admin::user()->id;
//        $goodsOrder->refunds_at = now();
//        $goodsOrder->payment_status = 3;
//        $goodsOrder->save();
//        return $this
//            ->response()
//            ->success('退款成功')
//            ->refresh();
    }

    public function form()
    {
//        $id = $this->payload['id'] ?? null;
        $this->textarea('refund_reason', '退款理由')->required();
    }
}
